﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using codewriter;

namespace sqlDALgen.Loaders
{
    public class TableLoader : IEntityDataLoader
    {
        public TemplateData Load(string name, string schema, string connectionString)
        {
            var tables = DbUtil.LoadTableSchema(name, schema, connectionString);

            var data = new TemplateData {
                {
                    "entity", new TemplateData
                                    {
                                        { "from", new TemplateData
                                                    {
                                                        {
                                                            "0", new TemplateData 
                                                                        {
                                                                            { "as", TemplateData.ValueNode(name[0]) },
                                                                            { "joinType", TemplateData.ValueNode("") },
                                                                            { "on", TemplateData.ValueNode("") },
                                                                            { "tables", tables["tables"] },
                                                                        }
                                                        }
                                                    } 
                                        },
                                        { "gets", new TemplateData() }
                                    }
                }
            };

            data.ResolvePath("entity.from.0").Value = String.Format("[{0}].[{1}]", schema, name);
            var gets = data.ResolvePath("entity.gets");

            var cnt = 0;
            foreach (var key in tables.ResolvePath("tables.1.items"))
            {
                var get = new TemplateData { { "as", TemplateData.ValueNode(key.Value["column_name"].ToString()) } };
                get.Value = String.Format("{0}.{1}", name[0], key.Value["column_name"].ToString());

                gets.Add(cnt.ToString(), get);

                cnt++;
            }

            return data;
        }
    }
}
